// pages/shop_auth/index.js
import {
    getReLogin,
    SubmitReLogin
  } from "../../api/index.js"
  import {getShopAuthApi} from "../../api/user.js"
  const md5 = require('../../utils/md5code.js');
  import {
      HEADER,
      CACHE_TOKEN,
      HTTP_REQUEST_URL,
      HTTP_REQUEST_FILE_URL
  } from '../../config.js';
  
  Page({
      /**
       * 页面的初始数据
       */
      data: {
          scrollViewHeight: 0,
          verifyStatus: '',
          noticeList: [
              {
                  icon: "",
                  title: "提交认证材料，认证后可以享受更多专属服务噢～",
                  authState: 0,
                  background: "#FFF8C5",
                  color: "#262626"
              },
              {
                  icon: "/images/icon/icon／icon_warn@2x.png",
                  title: "审核中",
                  authState: 1,
                  background: "#CCE9FF",
                  color: "#262626"
              },
              {
                  icon: "/images/icon/icon／icon_tick@2x.png",
                  title: "认证成功",
                  authState: 3,
                  background: "#262626",
                  color: ""
              },
              {
                  icon: "/images/icon/icon／icon_wrong@2x.png",
                  title: "认证未通过。",
                  authState: 2,
                  background: "#FFDFDE",
                  color: "#FA5650"
              },
              {
                icon: "/images/icon/icon／icon_wrong@2x.png",
                title: "认证成功，重新认证审核不通过，原因：",
                authState: 4,
                background: "#FFDFDE",
                color: "#FFF8C5"
            },
              {
                icon: "/images/icon/icon／icon_tick@2x.png",
                title: "认证成功，重新审核中",
                authState: 5,
                background: "#FFC107",
                color: "#FFF8C5"
            },
          ],
          authState: 0,
          isAddress: false,
          storeAddress: "",
          cascaderValue: "",
          options: [],
          shopInnerList: [],
          shopInner: [],
          IDCard: "",
          IdCardUrl: "",
          IDCardBack: "",
          ShopFrontPhoto: "",
          businessLicense: "",
          formData: {
              card: "",
              idnumber: "",
              truename: "",
              address: "",
              outroom: "",
              inroom: "",
              areaid: "",
              company: "",
              credit_code: "",
              provinceId: "",
              province: "",
              cityId: "",
              city: "",
          },
          is_reset:0,
          shopid: "",
          fieldNames: {
              text: 'name',
              value: 'id',
              children: 'children',
          }, // 自定义字段名称
          disabled: false
      },
  
      /**
       * 选择经营所在地回调函数方法
       */
      handleSelAddress() {
          this.setData({
              isAddress: true
          })
      },
  
      /**
       * 全部选项选择完成后触发
       * @param {*} e 
       */
      handleFinish(e) {
          const { selectedOptions, value } = e.detail;
          console.log(e);
          const storeAddress = selectedOptions
              .map((option) => option.text || option.name)
              .join('/');
          this.setData({
              storeAddress,
              cascaderValue: value,
              isAddress: false
          })
  
      },
       signatureProcess(data) {
          let keys = Object.keys(data).sort()
          let query = keys.map(key => {
              return `${key}=${data[key]}`
          }).join('&')
          let signStr = md5.hexMD5(query).toUpperCase() + "code=APPStatic#@#&"
          let signFinal = md5.hexMD5(signStr).toUpperCase()
          return signFinal
      },
  
  
      /**
       * 文件上传回调函数方法
       * @param {*} e 
       */
      handleUpdAfterRead(e) {
          console.log(e)
          console.log(e.detail)
          let type = e.currentTarget.dataset.type
          let file = e.detail
          console.log("e.detail", e.detail)
          console.log("type", type)
          switch (type) {
              case "inner":
                  this.parseUrl(file[file.length - 1].url).then(res => {
                    this.setData({
                      shopInner: this.data.shopInner.concat(HTTP_REQUEST_FILE_URL + res.imgsrc[0])
                    })
                  });
  
                  break;
              case "IDCard":
                  this.parseUrl(file[0].url).then(res => {
                    this.setData({
                      IdCardUrl: HTTP_REQUEST_FILE_URL + res.imgsrc[0]
                    })
                  });
                  break;
              case "IDCardBack":
                  this.parseUrl(file[0].url).then(res => {
                    this.setData({
                      IDCardBack: HTTP_REQUEST_FILE_URL + res.imgsrc[0]
                    })
                  });
                  break;
              case "BusinessLicense":
                  this.parseUrl(file[0].url).then(res => {
                    console.log(res)
                    this.setData({
                      businessLicense: HTTP_REQUEST_FILE_URL + res.imgsrc[0],
                    })
                    console.log(this.data.businessLicense)
                  });
                  break;
              case "ShopFrontPhoto":
                  this.parseUrl(file[0].url).then(res => {
                    this.setData({
                      ShopFrontPhoto: HTTP_REQUEST_FILE_URL + res.imgsrc[0]
                    })
                  });
                  break;
          }
      },
  
      parseUrl(url){let that = this
        const commonParams = {
          sys_type: 'app',
          version_name: '6.16.0',
          client_device: 'wechat_xcx',
          timestamp: parseInt(Date.now() / 1000),
          token: wx.getStorageSync(CACHE_TOKEN)
        }
        commonParams['sign'] = that.signatureProcess(commonParams)
        return new Promise((resolve, reject) => {
          wx.uploadFile({
            url: 'https://static.chonglaoban.cn/FileOperate/multiImageUpload',
            filePath: url,
            name: 'imgFile',
            header: {
              "Content-Type": "multipart/form-data"
            },
            formData: commonParams,
            success: function (res) {
              res.data = JSON.parse(res.data)
              res.data.data = JSON.parse(that.base64_decode(res.data.data))
              console.log(res)
              resolve(res.data.data)
            },
            fail: function(err) {
                console.error('请求失败', err);
                reject(err)
            }
          })
          wx.hideLoading();
        })
      },
      handleUpdDel(e){
  
        const{ file } = e.detail
        console.log("chuanguolaile",file)
        let list = this.data.shopInnerList.filter(item => item.url != file.url)
        let inner = this.data.shopInner.filter(item => item != file.url)
        this.setData({
          shopInnerList: list,
          shopInner:inner
        })
      },
  
      handleUpdDelIDCard() {
        this.setData({
          IDCard: "",
          IdCardUrl: "",
        })
        console.log(this.data.IdCardUrl)
      },
      handleUpdDelIDCardBack() {
        this.setData({
          IDCardBack: "",
        })
      },
      handleUpdDelBusinessLicense() {
        this.setData({
          businessLicense: "",
          BusinessLicense: "",
        })
      },
      handleUpdDelShopFront() {
        this.setData({
          shopFrontPhoto: "",
          ShopFrontPhoto: "",
        })
      },
      /**
       * 提交认证
       */
      handleSubmit(e) {
          const {
            idnumber,
            address,
            cascaderValue,
            company,
            credit_code,
            truename,
          } = e.detail.value
          console.log('this.data.IDCardBack', this.data.IDCardBack)
          console.log("e.detail.value", e.detail.value)
          if (!truename) return getApp().Tips({ title: '请输入收件人！' });
          if (!idnumber) return getApp().Tips({ title: '请输入经营者身份证号码！' });
          if (!company) return getApp().Tips({ title: '请输入公司名称！' });
          if (!credit_code) return getApp().Tips({ title: '请输入统一社会信用代码！' });
          if (!cascaderValue) return getApp().Tips({ title: '请选择选择省市区！' });
          if (!address) return getApp().Tips({ title: '请输入详细地址！' });
  
          if (!this.data.IdCardUrl) return getApp().Tips({ title: '请上传身份证人像面！' });
          if (!this.data.IDCardBack) return getApp().Tips({ title: '请上传身份证国徽面！' });
          if (!this.data.businessLicense) return getApp().Tips({ title: '请上传营业执照照片！' });
          if (!this.data.ShopFrontPhoto) return getApp().Tips({ title: '请上传店门头照片！' });
          if (!this.data.shopInner && this.data.shopInner.length < 1) return getApp().Tips({ title: '请上传店内部照片！' });
          getReLogin({
            act: 'audit_new',
            licence: this.data.businessLicense,
            card: this.data.IDCardUrl,
            outroom: this.data.ShopFrontPhoto,
            inroom: this.data.shopInner[0],
            truename: truename,
            idnumber: idnumber,
            cityid: this.data.formData.cityId,
            address: address,
            company: company,
            card_back: this.data.IDCardBack,
            credit_code: credit_code,
            // areaid: ,
            is_reset: this.data.authState == 0 ? 0 : 1,
            shopid: this.data.shopid,
          }).then(res => {
            console.log('店铺认证', res)
            if (res.result == 101) {
              getApp().Tips({title: msg})
            }else{
              getApp().Tips({title: "提交成功"})
  
            }
          })
      },
  
      /**
           * 计算页面可滚动区域的动态高度
           */
      computeScrollViewHeight() {
          let that = this
          let query = wx.createSelectorQuery().in(this)
          query.select('.header').boundingClientRect()
          query.exec(res => {
              let headerHeight = res[0].height;
              let winHeight; // 窗口可使用高度
              wx.getSystemInfo({
                  success: (res) => {
                      winHeight = res.windowHeight
                  }
              })
              let scrollHeight = winHeight - headerHeight; // 滚动区域高度
              that.setData({
                  scrollViewHeight: scrollHeight
              })
          })
      },
  
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad() {
         let shopid = wx.getStorageSync("USER").shopid
         this.setData({
          shopid: shopid
         })
        getShopAuthApi({
          act: 'licence_info_new',
        }).then(res => {
          console.log('是是是',res)
          let status = res.status;
          let verify = res.verify;
          console.log("verifyverifyverify",verify)
          if (verify && verify.verify_status) {
            //待审核，看是否已经撤销
            if (verify.verify_status == 0) {
              let is_submit = verify.is_submit;
              if (is_submit == 0) {
                if (status == 5) {
                  //认证成功同时有新材料待审核
                  this.setData({
                    authState: 5,
                    disabled: true
                  })
                  //认证详情页面展示verify里面的数据
                  this.getFromVerify(res);
                } else {
                  //待审核
                  this.setData({
                    authState: 1,
                    disabled: true
                  })
                  //认证详情页面展示verify里面的数据
                  this.getFromVerify(res);
                }
              } else {
                if (status == 5) {
                  //认证成功
                  this.setData({
                    authState: 3,
                    disabled: true
                  })
                  //认证详情页面展示dic的数据
                  this.getFromDic(res);
                } else if (status == 1) {
                  //认证失败
                  this.setData({
                    authState: 2,
                    disabled: true
                  })
                  //认证详情页面展示dic的数据
                  this.getFromDic(res);
                } else {
                  //未提交
                  this.setData({
                    authState: 0,
                    disabled: false
                  })
                  //认证详情页面展示dic的数据
                  this.getFromDic(res);
                }
              }
            } else {
              if (status == 5) {
                if (verify.verify_status == 1) {
                  //"认证成功，重新认证审核不通过，原因：\(verify["reason"])"
                  this.setData({
                    authState: 4,
                    disabled: true
                  })
                  //认证详情页面展示verify里面的数据
                  this.getFromVerify(res);
                } else {
                  //认证成功
                  this.setData({
                    authState: 3,
                    disabled: true
                  })
                  //认证详情页面展示dic的数据
                  this.getFromDic(res);
                }
              } else if (status == 1) {
                //认证失败
                this.setData({
                  authState: 2,
                  disabled: true
                })
                if (verify.verify_status == 1) {
                  //认证详情页面展示verify里面的数据
                  this.getFromVerify(res);
                } else {
                  //认证详情页面展示dic的数据
                  this.getFromDic(res);
                }
              } else {
                //未提交
                this.setData({
                  authState: 0,
                  disabled: false
                })
                //认证详情页面展示dic的数据
                this.getFromDic(res);
              }
            }
          } else {
            if (status == 5) {
              //认证成功
              this.setData({
                authState: 3,
                disabled: true
              })
              //认证详情页面展示dic的数据
              this.getFromDic(res);
            } else if (status == 1) {
              //认证失败
              this.setData({
                authState: 2,
                disabled: true
              })
              //认证详情页面展示dic的数据
              this.getFromDic(res);
            } else {
              //未提交
              this.setData({
                authState: 0,
                disabled: false
              })
              //认证详情页面展示dic的数据
              this.getFromDic(res);
            }
          }
        })
        console.log(this.data.authState)
      },
  
      handleEdit() {
        this.setData({
          disabled: false
        })
        console.log(this.data.disabled)
      },
  
      getFromDic(res) {
          this.data.formData = res
          this.data.formData.provinceId = res.address.proviceId
          this.data.formData.province = res.address.provice
          this.data.formData.cityId = res.address.cityId
          this.data.formData.city = res.address.city
          this.data.formData.address = res.address.detail
          wx.nextTick(
            this.setData({
              formData: this.data.formData,
              IDCardBack: this.data.formData.card_back ? this.data.formData.card_back : '',
              IdCardUrl: this.data.formData.card ? this.data.formData.card : '',
              ShopFrontPhoto: this.data.formData.outroom ? this.data.formData.outroom : '',
              businessLicense:  this.data.formData.licence ? this.data.formData.licence : '',
              storeAddress: this.data.formData.province + this.data.formData.city,
              shopInnerList: this.data.formData.inroom ? [{url: this.data.formData.inroom}]: [],
              shopInner: this.data.formData.inroom ? [this.data.formData.inroom] : [],
            })
          )
          console.log(this.data.formData)
          console.log(this.data.shopInnerList)
          console.log(this.data.shopInner)
      },
  
  
      getFromVerify(res) {
        console.log( res.verify)
        this.data.formData = res.verify
        this.data.formData.provinceId = res.verify.address.proviceId
        this.data.formData.province = res.verify.address.provice
        this.data.formData.cityId = res.verify.address.cityid
        this.data.formData.city = res.verify.address.city
        this.data.formData.address = res.verify.address.detail
        wx.nextTick(
          this.setData({
            formData: this.data.formData,
            IDCardBack: this.data.formData.card_back ? this.data.formData.card_back : '',
            IdCardUrl: this.data.formData.card ? this.data.formData.card : '',
            ShopFrontPhoto: this.data.formData.outroom ? this.data.formData.outroom : '',
            businessLicense:  this.data.formData.licence ? this.data.formData.licence : '',
            storeAddress: this.data.formData.province + this.data.formData.city,
            shopInnerList: this.data.formData.inroom ? [{url: this.data.formData.inroom}]: [],
            shopInner: this.data.formData.inroom ? [this.data.formData.inroom] : [],
          })
        )
        console.log(this.data.formData.cityId)
      },
  
      /**
       * 选择省市行政区回调函数方法
       * @param {*} e
       */
      handleSelCascader(e) {
          const {
              value,
              tabIndex,
              selectedOptions
          } = e.detail
          // 遍历当前选中地址区间数组对象
          for (let i = 0; i < selectedOptions.length; i++) {
              if (value == selectedOptions[i].id) {
                  // 根据遍历的省级ID执行请求，获取省下级城市数组对象列
                  getReLogin({
                      act: "get_city_lists",
                      id: selectedOptions[i].id
                  }).then(res => {
                      if (res) {
                          this.data.options.forEach(item => {
                              res.forEach(items => {
                                  if (item.id == items.parentid) {
                                      item.children.push(items)
                                  }
                              })
                          })
                          switch (tabIndex) {
                              case 0:
                                  this.data.formData.provinceId = selectedOptions[tabIndex].id
                                  this.data.formData.province = selectedOptions[tabIndex].name
                                  this.setData({
                                      province: {
                                          id: selectedOptions[tabIndex].id,
                                          name: selectedOptions[tabIndex].name,
                                      }
                                  })
                                  break;
                              case 1:
                                  this.data.formData.cityId = selectedOptions[tabIndex].id
                                  this.data.formData.city = selectedOptions[tabIndex].name
                                  this.setData({
                                      city: {
                                          id: selectedOptions[tabIndex].id,
                                          name: selectedOptions[tabIndex].name,
                                      }
                                  })
                                  break;
                              case 2:
                                  this.setData({
                                      county: {
                                          id: selectedOptions[tabIndex].id,
                                          name: selectedOptions[tabIndex].name,
                                      }
                                  })
                                  break;
                              case 3:
                                  this.setData({
                                      town: {
                                          id: selectedOptions[tabIndex].id,
                                          name: selectedOptions[tabIndex].name,
                                      }
                                  })
                                  break;
                          }
                          // 重新赋值
                          this.setData({
                              options: this.data.options,
                          })
                      }
                  })
              }
          }
      },
      /**
       * 全部选项选择完成后触发
       * @param {*} e
       */
      handleFinish(e) {
          const {
              selectedOptions,
              value,
          } = e.detail;
  
          console.log(selectedOptions)
          const storeAddress = selectedOptions
              .map((option) => option.text || option.name).join('');
          this.setData({
              storeAddress,
              cascaderVal: value,
              isAddress: false,
          })
          console.log(this.data.formData);
      },
      /**
       * 获取省份列表
       * @param {*} Province
       */
      getHttpProvinceLists() {
          SubmitReLogin({
              act: "provinceLists",
          }).then(res => {
              if (res) {
                  res.forEach(item => {
                      item.children = []
                  })
                console.log('获取城市列表', res)
                  this.setData({
                      options: res
                  })
              }
          })
      },
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady() {
        this.getHttpProvinceLists()
  
      },
  
      /**
       * 生命周期函数--监听页面显示
       */
      onShow() {
          this.computeScrollViewHeight()
      },
  
      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide() {
  
      },
  
      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload() {
  
      },
  
      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh() {
  
      },
  
      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom() {
  
      },
  
      /**
       * 用户点击右上角分享
       */
      onShareAppMessage() {
  
      },
  
  
      base64_decode  (input)  { // 解码，配合decodeURIComponent使用
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = base64EncodeChars.indexOf(input.charAt(i++));
            enc2 = base64EncodeChars.indexOf(input.charAt(i++));
            enc3 = base64EncodeChars.indexOf(input.charAt(i++));
            enc4 = base64EncodeChars.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        return (output);
    },
  })